package com.ewzj.bigdata.mvp.model;

import android.app.Application;
import android.text.TextUtils;

import com.ewzj.bigdata.app.constants.AppConstants;
import com.ewzj.bigdata.mvp.model.api.service.CommonService;
import com.ewzj.bigdata.mvp.model.entity.resbean.BaseData;
import com.ewzj.bigdata.mvp.model.entity.resbean.SearchResultBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.ActivityScope;

import javax.inject.Inject;

import com.ewzj.bigdata.mvp.contract.SearchContract;
import com.jess.arms.utils.DataHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Function;


@ActivityScope
public class SearchModel extends BaseModel implements SearchContract.Model {
    private Gson mGson;
    private Application mApplication;
    private CommonService service;
    @Inject
    public SearchModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
        super(repositoryManager);
        this.mGson = gson;
        this.mApplication = application;
        this.service=repositoryManager.obtainRetrofitService(CommonService.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
        this.service=null;
    }

    @Override
    public Observable<List<SearchResultBean>> getHotSearch() {
        return service.getHotSearch().map(new Function<BaseData<List<SearchResultBean>>, List<SearchResultBean>>() {
            @Override
            public List<SearchResultBean> apply(BaseData<List<SearchResultBean>> listBaseData) throws Exception {
                return listBaseData.getData();
            }
        });
    }

    @Override
    public void saveSearchdata(SearchResultBean searchResultBean) {
        String str= DataHelper.getStringSF(mApplication,AppConstants.APPHISTORY);
        List<SearchResultBean> searchResultBeans;
        if (TextUtils.isEmpty(str)){
            searchResultBeans=new ArrayList<>();
        }else {
            searchResultBeans=mGson.fromJson(str, new TypeToken<List<SearchResultBean>>() {

            }.getType());
        }
        if (searchResultBeans.size()>=10){
            searchResultBeans.remove(0);
        }
        searchResultBeans.add(searchResultBean);
       DataHelper.setStringSF(mApplication,AppConstants.APPHISTORY,mGson.toJson(searchResultBeans));
    }
}